<template>
  <el-dialog :visible.sync="openDialog" :close-on-click-modal="false" style="max-width: 90vw;">
    <!--标题栏-->
    <template slot="title">
      <el-button type="primary" icon="el-icon-download" @click.stop="download">下载模板</el-button>
      <el-button v-if="tableData.length" type="primary" icon="el-icon-upload" @click="tableData = []">重新上传</el-button>
    </template>
    <div>
      <!--上传区域-->
      <upload-excel-component v-if="tableData.length === 0" :on-success="handleSuccess" :before-upload="beforeUpload" />
      <!--内容区域-->
      <div v-if="tableData.length">
        <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
          <el-table-column type="index" label="#" />
          <af-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
        </el-table>
        <div class="flex mg-top-20">
          <div class="flex1" />
          <el-button type="info" @click="openDialog = false">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
          <div class="flex1" />
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'

export default {
  name: 'OrmImport',
  components: { UploadExcelComponent },
  props: {
    columns: {
      type: Object, // { name: '姓名', age: '年龄' }
      default() {
        return {}
      }
    },
    templateFile: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      openDialog: false,
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    open() {
      this.tableData = []
      this.tableHeader = []
      this.openDialog = true
    },
    close() {
      this.openDialog = false
    },
    download() {
      if (this.templateFile) {
        location.href = this.templateFile
      } else {
        return this.$message.error('请设置模板文件')
      }
    },
    submit() {
      const data = []
      const keys = Object.keys(this.columns)
      if (keys.length === 0) {
        this.$message.error('请设置columns属性')
        return
      }
      for (const d of this.tableData) {
        const temp = {}
        for (const column in this.columns) {
          const key = this.columns[column]
          temp[column] = typeof d[key] !== 'undefined' ? d[key] : ''
        }
        data.push(temp)
      }
      this.$emit('submit', data)
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-dialog__body{
  padding-top: 0;
}
</style>
